package cn.gdcp.sql_list_contentprovider;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListener{
    private ListView lvStu;
    private Button btnAdd;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;
    private EditText edtKey;
    private ImageView ivSearch;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findViews();
  //      initStudentArrayList();
        adapter=new StuAdapter(MainActivity.this,studentArrayList,MainActivity.this);
        readDataFromDB();

        lvStu.setAdapter(adapter);
        lvStu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Student student = studentArrayList.get(i);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, EditActivity.class);
                intent.putExtra("STUDENT", student);
                startActivityForResult(intent, 1002);
            }
        });
    }



    /**
     * 从数据库读取学生列表
     */
    private void initStudentArrayList() {
        studentArrayList.add(new Student("17001","lisa", 18));
        studentArrayList.add(new Student("17002","lier", 18));
        studentArrayList.add(new Student("17003","liwu", 18));
        studentArrayList.add(new Student("17004","liqi", 18));
    }

    private void findViews() {
        lvStu=findViewById(R.id.lv_stu);
        btnAdd=findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });
        edtKey = findViewById(R.id.edt_key);
        ivSearch = findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = edtKey.getText().toString();
                searchFromDB(key);
            }
        });
        edtKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String key=edtKey.getText().toString();
                searchFromDB(key);
            }
        });
    }

    private void readDataFromDB() {
        /*String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);
        String sql = "create table if not exists student (stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);*/
        studentArrayList.clear();
       // Cursor cursor = db.query("student", null,null,
               // null,null,null,null,null);
        Uri uri = Uri.parse("content://com.gdcp.student/student");
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
       // db.close();
    }

    private void searchFromDB(String key) {
        String where = "name like '%"+key+"%' OR stuno like '%"+key+"%' OR age = '" + key + "'";

        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        studentArrayList.clear();
       // Cursor cursor = db.query("student", null, where,
       //         null,null,null,null,null);
        Uri uri = Uri.parse("content://com.gdcp.student/student");
        Cursor cursor = getContentResolver().query(uri,null,where,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 2001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);

            Student student =  new Student(stuno, name, age);
            addStudentToDB(student);
        }else if(resultCode == 3001){
            Student student = (Student) data.getSerializableExtra("STUDENT");
            updateStudentToDB(student);
        }

    }

    private void updateStudentToDB(Student student) {
        /*String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);*/

        /**第一种 组装语句
         String sql = "update student set name='"+student.getName()+"', " +
         "age = "+student.getAge()+" where stuno = '"+student.getStuno()+"'";
         db.execSQL(sql);
         db.close();
         readDataFromDB();*/

        // 第二种
        Uri uri = Uri.parse("content://com.gdcp.student/student");
        String where = "stuno = '"+student.getStuno()+"'";
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("age", student.getAge());
        int rows=getContentResolver().update(uri,values,where,null);
        Toast.makeText(MainActivity.this, "更新了"+ rows + "行", Toast.LENGTH_SHORT).show();
       /* db.update("student", values, where, null);
        db.close();*/
        readDataFromDB();
    }

    private void addStudentToDB(Student student) {
        /*String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);*/

        Uri uri = Uri.parse("content://com.gdcp.student/student");
        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());
        values.put("name", student.getName());
        values.put("age", student.getAge());
        getContentResolver().insert(uri, values);
       /* db.insert("student", null, values);
        db.close();*/
        readDataFromDB();
    }

    @Override
    public void del(Student student) {
        /*String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);*/
        /** 第一种 组装删除语句
         String sql = "delete from student where stuno='"+ student.getStuno() +"'";
         db.execSQL(sql);
         db.close();
         readDataFromDB();*/
        /** 第二种 使用delete接口
         String where = "stuno='" + student.getStuno() +"'";
         db.delete("student", where, null);
         db.close();
         readDataFromDB();*/
        // 第三种 使用带参数接口
        Uri uri = Uri.parse("content://com.gdcp.student/student");
        String where = "stuno= ? AND name = ?";
        String[] args = {student.getStuno(), student.getName()};
        int rows = getContentResolver().delete(uri, where, args);
        Toast.makeText(MainActivity.this, "删除了"+ rows + "行", Toast.LENGTH_SHORT).show();
       /* db.delete("student", where, args);
        db.close();*/
        readDataFromDB();
    }
}
